/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.pc.security;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.opu.pc.domain.domains.security.SecurityGroup;
import org.opu.pc.domain.domains.security.SecurityGroupHolder;
import org.opu.pc.domain.domains.security.User;
import org.opu.pc.ui.util.Logger;

/**
 *
 * @author yura
 */
public class SecurityActionFilter {

    private static final Logger logger = Logger.create(SecurityActionFilter.class);
    private static final Class<Object> OBJECT_CLASS = Object.class;

    public void cleanup(List actions){
        UserDetailsData details = UserDetailsData.getCurrentUser();
        if (details == null) {
            throw new NullPointerException("User details data is null");
        }

        User user = details.getUser();
        if (user == null) {
            throw new NullPointerException("User null");
        }

        logger.info("Selecting action for " + user);

        for (Iterator it = actions.iterator(); it.hasNext();) {
            Object action = it.next();
            Secured annotation = getAnnotation(action.getClass());
            if (annotation != null) {
                if (!available(user, annotation)){
                    it.remove();
                    logger.info(action.getClass().getName() + " not available for user");
                }
            } else {
                logger.warning(action.getClass().getName() + " do not have security level.");
            }
        }
    }

    private Secured getAnnotation(Class<?> clazz) {
        if (clazz == OBJECT_CLASS){
            return null;
        }

        Secured annotation = clazz.getAnnotation(Secured.class);
        if (annotation == null){
            return getAnnotation(clazz.getSuperclass());
        } else {
            return annotation;
        }
    }

    private boolean available(User user, Secured annotation){
        Set<SecurityGroupHolder> userGroups = user.getSecurityGroups();
        for (SecurityGroup group : annotation.value()) {
            if (userGroups.contains(new SecurityGroupHolder(group))){
                return true;
            }
        }
        return false;
    }
}
